package com.jams.goodox.activity.serve;

import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jams.goodox.BaseActivity;
import com.jams.goodox.R;
import com.jams.goodox.SePref;
import com.jams.goodox.adapter.viewHolder.RentingDetailViewHolder;
import com.jams.goodox.constant.AppConfig;
import com.jams.goodox.entity.Comment;
import com.jams.goodox.entity.Neighborhood;
import com.jams.goodox.entity.User;
import com.jams.goodox.entity.resp.NeighborCommentsResp;
import com.jams.goodox.entity.resp.NeighborDetailResp;
import com.jams.goodox.entity.resp.UserLisResp;
import com.jams.goodox.listen.SuccessListener;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.RentingService;
import com.jams.goodox.utils.CircleManager;
import com.jams.goodox.utils.CollectionUtils;
import com.jams.goodox.utils.DelayUtils;
import com.jams.goodox.utils.DeviceUtils;
import com.jams.goodox.utils.DialogUtils;
import com.jams.goodox.utils.ImageUtils;
import com.jams.goodox.utils.MessageDialog;
import com.jams.goodox.utils.StringUtils;
import com.jams.goodox.utils.StyleUtil;
import com.jams.goodox.widget.RefreshRecyclerView;
import com.jams.goodox.widget.mannger.RefreshLinearLayoutManager;
import com.jams.library.commonAdapter.RecycleCommonAdapter;
import com.jams.library.commonAdapter.RecycleCommonViewHolder;
import com.jams.library.listener.OnRecycleItemClickListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import retrofit2.Call;


/**
 * 个人发布的租房详情页
 *
 * create by 顾佳佳 on 2017/05/05
 */
public class PersonalRentingDetailActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener {

    @Bind(R.id.rcv_neighbor_comment)
    RefreshRecyclerView rcvNeighborComment;
    @Bind(R.id.sdv_circle_detail)
    SwipeRefreshLayout sdvCircleDetail;
    @Bind(R.id.iv_neighbour_bottom_left)
    ImageView ivNeighbourBottomLeft;
    @Bind(R.id.tv_neighbour_bottom_left)
    TextView tvNeighbourBottomLeft;
    @Bind(R.id.ly_neighbor_bottom_group)
    LinearLayout lyNeighborBottomGroup;
    private TextView tvRightMenu;

    public static final String ID = "ID";
    private RentingDetailViewHolder neighborDetailViewHolder;
    private Neighborhood neighborhood;
    private String id;
    private List<Comment> commentDataList;
    private int totalComments;//总的评论数
    private int curPage;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_personal_renting_detail;
    }

    @Override
    protected void init() {
        StyleUtil.titleBackKey(this,"详情");
        commentDataList = new ArrayList<>();
        tvRightMenu = (TextView) findViewById(R.id.head_right_tv);
        id = getIntent().getStringExtra(ID);
        sdvCircleDetail.setOnRefreshListener(this);
        View view = LayoutInflater.from(this).inflate(R.layout.renting_detail, null);
        neighborDetailViewHolder = new RentingDetailViewHolder(this, view);
        rcvNeighborComment.setLayoutManager(new RefreshLinearLayoutManager(this));
        rcvNeighborComment.setHasFixedSize(true);
        RecycleCommonAdapter commonAdapter;
        rcvNeighborComment.setAdapter(commonAdapter = new RecycleCommonAdapter<Comment>(this, commentDataList, R.layout.renting_comment_item) {
            @Override
            public void convert(RecycleCommonViewHolder helper, Comment item, int position) {
                setCommentData(helper, item, position);
            }

        });
        rcvNeighborComment.setLoadDataListener(new RefreshRecyclerView.LoadDataListener() {
            @Override
            public void onLoadMore() {
                getCommentList();
            }
        });
        commonAdapter.setHeaderView(view);
        onRefresh();
    }

    //获取邻里详情
    private void getNeighborDetail() {
        enqueue(createCallService(RentingService.class).getNeighborDetail(id), new RetrofitCallbackListener<NeighborDetailResp>() {
            @Override
            public void onSuccess(Call<NeighborDetailResp> call, NeighborDetailResp result) {
                sdvCircleDetail.setRefreshing(false);
                neighborhood = result.getData();
                setRightAction();
                setPraiseStatus();
                getJoinList(false);
            }

            @Override
            public void onError(String msg) {
                sdvCircleDetail.setRefreshing(false);
                neighborDetailViewHolder.setCommentTipStatus(true);
            }
        });
    }

    //获取留言列表
    private void getCommentList() {
        enqueue(createCallService(RentingService.class).getNeighborComments(id, curPage, AppConfig.PagSize), new RetrofitCallbackListener<NeighborCommentsResp>() {
            @Override
            public void onSuccess(Call<NeighborCommentsResp> call, NeighborCommentsResp result) {
                sdvCircleDetail.setVisibility(View.VISIBLE);
                lyNeighborBottomGroup.setVisibility(View.VISIBLE);
                sdvCircleDetail.setRefreshing(false);
                rcvNeighborComment.loadMoreComplete();
                if(result.getData() != null){
                    if (curPage == 1) {
                        commentDataList.clear();
                    }
                    rcvNeighborComment.setCanLoadMore(result.getData().getPageInfo().isHasMore());
                    commentDataList.addAll(result.getData().getResultList());
                    curPage++;
                    if (!CollectionUtils.hasData(commentDataList)) {
                        neighborDetailViewHolder.setCommentTipStatus(true);
                    } else {
                        neighborDetailViewHolder.setCommentTipStatus(false);
                    }
                    totalComments = result.getData().getPageInfo().getTotal();
                    neighborDetailViewHolder.setCommentCounts(totalComments);
                    rcvNeighborComment.notifyData();
                }else {
                    neighborDetailViewHolder.setCommentTipStatus(true);
                }
            }

            @Override
            public void onError(String msg) {
                sdvCircleDetail.setRefreshing(false);
                rcvNeighborComment.loadMoreComplete();
                neighborDetailViewHolder.setCommentTipStatus(true);
            }
        });
    }

    //获取加入、点赞的人的列表
    private void getJoinList(final boolean isUpdate) {
        enqueue(createCallService(RentingService.class).getJoinList("neighbor", neighborhood.getId(), 1, 5), new RetrofitCallbackListener<UserLisResp>() {
            @Override
            public void onSuccess(Call<UserLisResp> call, UserLisResp result) {
                if (result.getData() != null) {
                    if (!isUpdate) {//非局部刷新
                        neighborDetailViewHolder.setData(neighborhood, result.getData(),false);
                        getCommentList();
                    } else {//局部刷新
                        neighborDetailViewHolder.updateJoinList(result.getData());
                    }
                }
            }

            @Override
            public void onError(String msg) {
                sdvCircleDetail.setRefreshing(false);
            }
        });
    }

    //设置顶部右边菜单键
    private void setRightAction() {
        if (isMyself(neighborhood.getUserSimple().getId())) {
            tvRightMenu.setText(R.string.delete);
            tvRightMenu.setVisibility(View.VISIBLE);
            tvRightMenu.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    delCircle(neighborhood.getId());
                }
            });
        } else {
            tvRightMenu.setVisibility(View.GONE);
        }
    }

    //检查是否是自己
    private boolean isMyself(String id) {
        if (id == null) {
            return false;
        } else if (id.equals(SePref.getUserId())) {
            return true;
        }
        return false;
    }

    //删除邻里
    private void delCircle(final String id) {
        DialogUtils.deleteConfirm(this, "确定删除？", new SuccessListener() {
            @Override
            public void success() {
                CircleManager.delCircle(PersonalRentingDetailActivity.this, id, new SuccessListener() {
                    @Override
                    public void success() {
                        setResult(1993);
                        finish();
                    }
                });
            }
        });
    }

    //回复
    public void replayMessage(final Comment item, final int position) {
        final boolean isMySendMessage = item.getFromUser().getId().equals(SePref.getUserId());
        if (isMySendMessage) {
            setIsMyselfMenu(item, position);
        } else {
            setIsOtherMenu(item);
        }
    }

    //设置本人底部弹出菜单
    private void setIsMyselfMenu(final Comment item, final int position) {
        String strArray[];
        strArray = new String[]{getString(R.string.delete), getString(R.string.copy)};
        MessageDialog.showBottomMenu(this, strArray, new MessageDialog.MenuDialogOnItemClickListener() {
            @Override
            public void onItemClick(int index) {
                switch (index) {
                    case 1:
                        DialogUtils.deleteConfirm(PersonalRentingDetailActivity.this, "确定删除该评论？", new SuccessListener() {
                            @Override
                            public void success() {
                                CircleManager.delComment(PersonalRentingDetailActivity.this, item.getId(), new SuccessListener() {
                                    @Override
                                    public void success() {
                                        commentDataList.remove(position);
                                        neighborDetailViewHolder.setCommentCounts(totalComments - 1);
                                        rcvNeighborComment.notifyData();
                                        if (!CollectionUtils.hasData(commentDataList)) {
                                            neighborDetailViewHolder.setCommentTipStatus(true);
                                        } else {
                                            neighborDetailViewHolder.setCommentTipStatus(false);
                                        }
                                    }
                                });
                            }
                        });
                        break;
                    case 2:
                        DeviceUtils.copyToClipBoard(PersonalRentingDetailActivity.this, item.getContent());
                        break;
                    default:
                        break;
                }
            }
        });
    }

    //不是本人的底部菜单
    private void setIsOtherMenu(final Comment item) {
        if(item == null){
            return;
        }
        String strArray[];
        strArray = new String[]{getString(R.string.copy), getString(R.string.message_pri_msg), getString(R.string.replay_comment)};
        MessageDialog.showBottomMenu(this, strArray, new MessageDialog.MenuDialogOnItemClickListener() {
            @Override
            public void onItemClick(int index) {
                switch (index) {
                    case 1:
                        DeviceUtils.copyToClipBoard(PersonalRentingDetailActivity.this, item.getContent());
                        break;
                    case 2:
                        message(item.getFromUser());
                        break;
                    case 3:
                        Intent intent = new Intent(PersonalRentingDetailActivity.this, CommentActivity.class);
                        intent.putExtra("id", neighborhood.getId());
                        intent.putExtra("toUserId", item.getFromUser().getId());
                        intent.putExtra("msgId", item.getId());
                        intent.putExtra("toUserName", item.getFromUser().getNickName());
                        startActivityForResult(intent, 1991);
                        break;
                    default:
                        break;
                }
            }
        });
    }

    //私信
    private void message(User userInfo) {
        Intent intent = new Intent();
        intent.putExtra("userId", userInfo.getId());
        intent.putExtra("userName", userInfo.getNickName());
        intent.putExtra("msgReason", 1);
        startActivity(intent);
    }

    private void setPraiseStatus() {
        if (neighborhood.isPraise()) {
            tvNeighbourBottomLeft.setText("已赞");
            ivNeighbourBottomLeft.setBackgroundResource(R.mipmap.good_icon_orange);
            tvNeighbourBottomLeft.setTextColor(ContextCompat.getColor(this, R.color.orange));
        } else {
            tvNeighbourBottomLeft.setText("点赞");
            ivNeighbourBottomLeft.setBackgroundResource(R.mipmap.good_icon);
            tvNeighbourBottomLeft.setTextColor(ContextCompat.getColor(this, R.color.font_main));
        }
    }

    @OnClick({R.id.lv_neighbor_detail_bottom_left, R.id.lv_neighbor_detail_bottom_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.lv_neighbor_detail_bottom_left:
                final int actionType;
                if (neighborhood.isPraise()) {
                    actionType = 0;
                } else {
                    actionType = 1;
                }
                CircleManager.praise(this, neighborhood.getId(), actionType, new SuccessListener() {
                    @Override
                    public void success() {
                        if (actionType == 0) {
                            neighborDetailViewHolder.praise(false);
                            neighborhood.setPraise(false);
                        } else {
                            neighborDetailViewHolder.praise(true);
                            neighborhood.setPraise(true);
                        }
                        setPraiseStatus();
                    }
                });
                break;
            case R.id.lv_neighbor_detail_bottom_right:
                if(neighborhood == null){
                    return;
                }
                Intent intent = new Intent(PersonalRentingDetailActivity.this, CommentActivity.class);
                intent.putExtra("id", StringUtils.newString(neighborhood.getId()));
                startActivityForResult(intent, 1991);
                break;
        }
    }

    private void setCommentData(RecycleCommonViewHolder helper,final Comment comment,final int position) {
        helper.setSimpleDraweeView(R.id.sdv_neighbour_comment_portrait, StringUtils.newString(ImageUtils.getSmallUrl(comment.getFromUser().getPortraitUrl())));
        helper.setText(R.id.tv_neighbor_comment_name, StringUtils.newString(comment.getFromUser().getNickName()));
        helper.setText(R.id.tv_neighbor_comment_time, StringUtils.newString(comment.getInTime()));
        if (comment.getToUser() == null || TextUtils.isEmpty(comment.getToUser().getId())) {
            helper.setText(R.id.tv_neighbor_comment_content, StringUtils.newString(comment.getContent()));
        } else {
            String content = "回复" + comment.getToUser().getNickName() + ":" + StringUtils.newString(comment.getContent());
            SpannableStringBuilder style = new SpannableStringBuilder(content);
            style.setSpan(new ForegroundColorSpan(ContextCompat.getColor(PersonalRentingDetailActivity.this, R.color.main_theme)), 2, comment.getToUser().getNickName().length() + 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            ((TextView) helper.getView(R.id.tv_neighbor_comment_content)).setText(style);
        }
        helper.setOnItemClickListener(new OnRecycleItemClickListener() {
            @Override
            public void itemClick() {
                replayMessage(comment, position);
            }
        });
    }

    @Override
    public void onRefresh() {
        DelayUtils.doAfterDelay(100, new DelayUtils.DelayDoListener() {
            @Override
            public void doAction() {
                sdvCircleDetail.setRefreshing(true);
                curPage = 1;
                getNeighborDetail();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1991) {
            switch (resultCode) {
                case 1992://评论成功
                    curPage = 1;
                    getCommentList();
                    break;
                default:
                    break;
            }
        }
    }
}
